;(function(window, document) {
    // props
    var defaultSettings = {
        dragId : 'dragDiv',
        dragMoveBtn : 'dragMoveBtn',
        imageDiv : 'imageDiv',
        dragInfo : 'dragInfo',
        dragRemove : 'dragRemove',
        dragSourceTop : 'dragSourceTop',
        dragSourceLeft : 'dragSourceLeft',
        dragDivChange : 'dragDivChange',
        dragLeft : 'dragLeft',
        dragRight : 'dragRight',
        dragSourceInfo : 'dragSourceInfo',
        dragBanItem:'dragBanItem',
        placeX : 0,
        placeY : 0,
        isdraggrid:'isdraggrid',
        dragitemid:'dragitemid',
    };
  
    function dragLay(options) {
        var _this = this;
         _this = Object.assign(_this, defaultSettings, options || {});
        _this.init = function() {
            setTimeout(function(){
                _this._init();
            },0);
        };

        setTimeout(function(){
            _this._init();
        },0);
        // var resizeTimer ;
        // window.onresize = function() {
        //     clearTimeout(resizeTimer);
        //     resizeTimer = setTimeout(function(){
        //         _this._init();
        //     },500);
        // };

    }
    dragLay.prototype = {
        _init: function() {
            this.oUl= document.getElementById(this.dragId);
            // 异常处理
            if(!this.oUl) return false;
            this.oUlTop = this.oUl.offsetTop + this.placeY;
            this.oUlLeft = this.oUl.offsetLeft + this.placeX;
            this.aLi = this.oUl.querySelectorAll('.'+this.dragMoveBtn);
            this.aDel = this.oUl.querySelectorAll('.'+this.dragRemove);
            this.aInfo = this.oUl.querySelectorAll('.'+this.dragInfo);
            this.aTop = document.querySelectorAll('.'+this.dragSourceTop+ '> li');
            this.aLeft = document.querySelectorAll('.'+this.dragSourceLeft+ '> li');
            this.disX = 0;
            this.disY = 0;
            this.leftTem = [];
            for(var t = 0; t < this.aInfo.length; t++){
                if(this.aInfo[t].getAttribute(this.isdraggrid) === '1'){
                    this._styleChange(this.aInfo[t]);
                }
            }
            
            
            this.iconL =  this.oUl.querySelectorAll('.'+this.dragLeft);
            this.iconR =  this.oUl.querySelectorAll('.'+this.dragRight);
            for(var il=0;il < this.iconL.length;il++){
                this._divChange(this.iconL[il],'left');
            }

            for(var rl=0;rl < this.iconR.length;rl++){
                this._divChange(this.iconR[rl],'right');
            }
            for(var i=0;i<this.aLi.length;i++){
                this.aLi[i].index = i;
                this._setDrag(this.aLi[i]);
            }
            for(var h=0;h<this.aDel.length;h++){
                this.aDel[h].index = h;
                if(!!this.aDel[h].getAttribute(this.dragitemid)){
                    this.leftTem.push(this.aDel[h].getAttribute(this.dragitemid));
                }
                this._removeDrag(this.aDel[h]);
            }
            for(var j = 0; j < this.aLeft.length;j++){
                this.aLeft[j].index = j;
                var dargObj = this.aLeft[j].querySelector('.'+this.dragRemove);
                var dargId = (!!dargObj && dargObj.getAttribute(this.dragitemid) )? dargObj.getAttribute(this.dragitemid) : null;

                if(!!dargId && this.leftTem.indexOf(dargId) < 0){
                    this._setDrag(this.aLeft[j],this.oUl,dargId);
                    this.aLeft[j].classList.remove(this.dragBanItem);
                }else{
                    this.aLeft[j].classList.add(this.dragBanItem);
                }
            }

            for(var j = 0; j < this.aTop.length;j++){
                this.aTop[j].index = j;
                this._setDrag(this.aTop[j],this.oUl);

            }

            if(!!this.extend){
                for(var fnx in this.extend){
                    this.extend[fnx]();
                }
            }
        },
        _removeDrag: function(obj){
            var _this = this;
            obj.onclick = function(){
              this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
              _this._init();
            };
        },
        _styleChange:function(obj){
            if(!obj.querySelector('.'+this.dragLeft)){
                var lDiv = this._createDiv('div',{'class':this.dragLeft});
                var RDiv = this._createDiv('div',{'class':this.dragRight});
                var changeDiv = this._createDiv('div',{'class':this.dragDivChange});
                changeDiv.appendChild(lDiv);
                changeDiv.appendChild(RDiv);
                if(obj.children[0]){
                    obj.insertBefore(changeDiv, obj.children[0]);
                }else{
                    obj.appendChild(changeDiv);
                }
                this._divChange(lDiv,'left');
                this._divChange(RDiv,'right');
            }
            var oheight = obj.clientHeight;
            obj.querySelector('.'+this.dragLeft).style.height = oheight + 'px';
            obj.querySelector('.'+this.dragRight).style.height = oheight + 'px';
        },
        _divChange:function(obj,_dir){
            var _this = this;
            var oldW = obj.parentNode.parentNode.parentNode.clientWidth - 2;
            var oldL = 0;
            // 外部顶级容器style
            var elem = _this._objStyle(obj.parentNode.parentNode.parentNode.parentNode);
            var elemPL = parseInt(elem.paddingLeft,10);
            var elemPR = parseInt(elem.paddingRight,10);
            
            obj.onmousedown = function(event){
                event = event || window.event;
                if(event.stopPropagation){
                    event.stopPropagation();
                }else{
                    event.cancelBubble = true;
                }

                var pageX = event.pageX || event.clientX + _this._getScroll().scrollLeft;


                var elemInfo = _this._objStyle(obj.parentNode.parentNode);
                var elemInfoML = parseInt(elemInfo.marginLeft,10);
                var oW = obj.parentNode.parentNode.clientWidth;
                var moveLW = 0;
                var moveRW = 0;
                var parentObj = obj.parentNode.parentNode;
                document.onmousemove = function(e){

                    e = e || window.event;
                    if(e.stopPropagation){
                        e.stopPropagation();
                    }else{
                        e.cancelBubble = true;
                    }

                    var pageXX = e.pageX || e.clientX + _this._getScroll().scrollLeft;

                    var moveW = pageXX - pageX;

                    if(_dir === 'left'){
                        if((oW - moveW)  <= oldW && (oldL + moveW)>=0 && (oW - moveW - ( elemPL + elemPR ) )>=0){
                            // 百分比模式
                            parentObj.style.width = ((oW - moveW - ( elemPL + elemPR ) )/oldW)*100+'%';
                            // console.log(parseInt((oldL + moveW)/oldW*100,10));
                            parentObj.style.marginLeft = (oldL + moveW)/oldW*100+ '%';
                            // 像素模式
                            // parentObj.style.width = (oW - moveW - ( elemPL + elemPR ) )+ 'px';
                            // parentObj.style.marginLeft = oldL + moveW + 'px';
                            moveLW = moveW;
                        }
                    }else if(_dir === 'right'){
                        if((oW + moveW)  <= oldW && (oldW - elemInfoML - 2) >= (oW + moveW)){
                            if(( oW +  moveW - ( elemPL + elemPR))>=0){

                                
                                // 百分比模式
                                parentObj.style.width = (( oW +  moveW - ( elemPL + elemPR))/oldW)*100+ '%';
                                // 像素模式
                                // parentObj.style.width = ( oW +  moveW - ( elemPL + elemPR))+ 'px';
                            }
                        }
                    }
                };
                
                document.onmouseup = function(e){
                    oldL += moveLW;
                    document.onmousemove = null;
                    document.onmouseup = null;
                    return false;
                };
                return false;
            };
        },
        // 创建节点
        _createDiv:function(obj,props){
            var oDiv = document.createElement(obj);
            for (var value in props) {
                oDiv.setAttribute(value, props[value])
            }
            return oDiv;
        },
        // 占位元素碰撞检测
        _findImage: function(obj){
            var isBool = false;
            if(obj){
                var oDiv=document.querySelector('.'+this.imageDiv);
                var rectObj = oDiv.getBoundingClientRect();
                isBool = this._colTest(obj,{
                    offsetWidth:oDiv.offsetWidth,
                    offsetHeight:oDiv.offsetHeight,
                    offsetLeft:rectObj.left - this.placeX,
                    offsetTop:rectObj.top - this.placeY,
                });

            }
            return isBool;
        },
        // 内部距离最近
        _findMinIns: function(obj,_obj){
            var minDis = 999999999;
            var minIndex = -1;
            var _optObj = _obj.querySelectorAll('.'+this.dragInfo);
            for(var i = 0; i < this.aInfo.length; i ++){
                var isStop = false;
                for(var ii = 0;ii<_optObj.length;ii++){
                    if(_optObj[ii]==this.aInfo[i]){
                        isStop = true;
                    }
                }
                if(isStop)continue;

                var item = this.aInfo[i],
                rect = item.getBoundingClientRect(),
                osTop = (document.documentElement.scrollTop || document.body.srcollTop || 0),
                osLeft = (document.documentElement.scrollLeft || document.body.scrollLeft || 0);
                item = {
                    offsetWidth:this.aInfo[i].offsetWidth,  
                    offsetHeight:this.aInfo[i].offsetHeight,
                    offsetLeft:rect.left - this.placeX + osLeft,
                    offsetTop:rect.top - this.placeY + osTop - 10,
                };

                if(this._colTest(obj,item)){
                    var dis = this._getDis(obj,item);
                    if(dis<minDis){
                        minDis = dis;
                        minIndex = i;
                    }
                }
            }
            if(minIndex==-1){
                return null;
            }else{
                return this.aInfo[minIndex];
            }
        },
        // 外部距离最近的
        _findMinOut: function(obj,_obj){
            var minDis = 999999999;
            var minIndex = -1;
            var _optObj = _obj.querySelectorAll('.'+this.dragMoveBtn);
            for(var i=0;i<this.aLi.length;i++){
                var isStop = false;
                for(var ii = 0;ii<_optObj.length;ii++){
                    if(_optObj[ii]==this.aLi[i]){
                        isStop = true;
                    }
                }
                if(isStop)continue;
                if(this._colTest(obj,this.aLi[i].parentNode.parentNode)){
                    var dis = this._getDis(obj,this.aLi[i].parentNode.parentNode);
                    if(dis<minDis){
                        minDis = dis;
                        minIndex = i;
                    }
                }
            }
            if(minIndex==-1){
                return null;
            }else{
                return _obj === this.aLi[minIndex].parentNode.parentNode ? null : this.aLi[minIndex].parentNode.parentNode;
            }
        },
        // 外部占位节点
        _occupyDivOut: function(obj){
            var oDiv=document.querySelector('.'+this.imageDiv);
            if(obj){
                obj.parentNode.insertBefore(oDiv,obj);
            }else{
                this.oUl.appendChild(oDiv);
            } 
        },
        _occupyDivIns: function(obj){
            var oDiv=document.querySelector('.'+this.imageDiv);
            if(obj){
                obj.appendChild(oDiv);
            }
        },
       
        // 拖动操作准备style
        _optStyle: function (obj,ins,dargId){
            var objStyle = this._objStyle(obj);
            rect = obj.getBoundingClientRect();
            if(ins){
                obj.style.left = rect.left - parseInt(objStyle.marginLeft,10) + 'px';
                if(!!dargId){
                    obj.style.top = rect.top - this.oUlTop - parseInt(objStyle.marginTop,10) + 'px';
                    obj.style.display = 'none';
                }else{
                    obj.style.top = rect.top - parseInt(objStyle.marginTop,10) + 'px';
                }
            }else{

                obj.style.left = rect.left - this.oUlLeft - parseInt(objStyle.marginLeft,10) + 'px';
                obj.style.top = rect.top - this.oUlTop + (this._getScroll().scrollTop || 0) - parseInt(objStyle.marginTop,10) + 'px';
            }
            obj.style.maxWidth = (obj.clientWidth - parseInt(objStyle.paddingLeft,10) - parseInt(objStyle.paddingRight,10)) + 'px';
            obj.style.position = 'absolute';
        },
        // 拖动完毕
        _clearStyle: function(obj){
            obj.style.left = '';
            obj.style.top = '';
            obj.style.maxWidth = '';
            obj.style.position = '';
        },
        // 源style获取
        _objStyle: function(obj){
            var oStyle = {};
            // ie兼容
            if (window.getComputedStyle) {
                oStyle = getComputedStyle(obj, null)
            } else {
                oStyle = obj.currentStyle;
            }
            return oStyle;
        },
        // 镜像
        _imageDiv: function(obj,ins){
            var oDiv=document.createElement('div');
            oDiv.setAttribute('class',this.imageDiv);
            var objStyle = this._objStyle(obj);
            // 边的距离2
            oDiv.style.height = (obj.clientHeight - 2) + 'px';
            oDiv.style.marginTop = objStyle.marginTop;
            oDiv.style.marginBottom = objStyle.marginBottom;
            oDiv.style.marginLeft= objStyle.marginLeft;
            oDiv.style.marginRight = objStyle.marginRight;
            if(ins){
                ins.appendChild(oDiv);
                var newObj = obj.cloneNode(true);
                insertAfter(newObj,obj);
            }else{
                obj.parentNode.insertBefore(oDiv,obj);
            }
        },
         // 操作完成
         _stopOpt: function(obj,ins){
            var stopObj = obj;
            if(ins){
                stopObj = stopObj.querySelector('.'+this.dragSourceInfo).children[0];
                obj.parentNode.removeChild(obj);
            }
             
            var oDiv=document.querySelector('.'+this.imageDiv);
            insertAfter(stopObj,oDiv);
            this._deleteImage();
        },
        // 删除占位
        _deleteImage: function(){
            var oDiv=document.querySelector('.'+this.imageDiv);
            if(oDiv){
                oDiv.parentNode.removeChild(oDiv);
            }
        },
        //拖拽
        _setDrag: function(btn,ins,dargId){
            var _this = this;
            var obj = ins ? btn : btn.parentNode.parentNode;
            var objStyle = this._objStyle(obj);
            btn.onmousedown = function(event){
                
                event = event || window.event;
                if(event.stopPropagation){
                    event.stopPropagation();
                }else{
                    event.cancelBubble = true;
                }

                var pageX = event.pageX || event.clientX + _this._getScroll().scrollLeft;
                var pageY = event.pageY || event.clientY + _this._getScroll().scrollTop;
                
                _this.oUl.style.width = _this.oUl.offsetWidth + 'px';
                _this.oUl.style.height = _this.oUl.offsetHeight + 'px';
                if(ins){
                    // 镜像       
                    _this._imageDiv(obj,ins);
                    // 拖动操作准备
                    _this._optStyle(obj,ins,dargId);
                }else{
                    // 拖动操作准备
                    _this._optStyle(obj,ins);
                    // 镜像       
                    _this._imageDiv(obj,ins);
                }
                obj.style.zIndex = 100;
                //当鼠标按下时计算鼠标与拖拽对象的距离
                
                _this.disX = pageX + _this._getScroll().scrollLeft - obj.offsetLeft;
                _this.disY = pageY - obj.offsetTop;
                
                //当鼠标拖动时计算div的位置
                document.onmousemove = function(events){
                    events = events || window.event;
                    if(events.stopPropagation){
                        events.stopPropagation();
                    }else{
                        events.cancelBubble = true;
                    }
                    var osTop = _this._getScroll().scrollTop || 0;
                    var osLeft = _this._getScroll().scrollLeft || 0;
                    
                    var pageXX = events.pageX || events.clientX + osLeft;
                    var pageYY = events.pageY || events.clientY + osTop;
                    _this.oUl.style.width = '';
                    _this.oUl.style.height = '';
                    var l = pageXX - _this.disX + osLeft - parseInt(objStyle.marginLeft,10);
                    var t = pageYY - _this.disY - parseInt(objStyle.marginTop,10);
                    obj.style.left = l + "px";
                    obj.style.top = (t) + "px";
                    
                    clearTimeout(_this.timer);
                    
                    _this.timer = setTimeout(function(){
                        // 坐标实例
                        var objs = {
                            offsetTop:pageYY - _this.oUlTop,
                            offsetLeft:pageXX - _this.oUlLeft,
                            offsetWidth:0,
                            offsetHeight:0,
                        };
                        var isImage = _this._findImage(objs);
                        
                        if(!isImage){
                            var oIns = _this._findMinIns(objs,obj);
                            var oNear = _this._findMinOut(objs,obj);
                            if(oIns){

                                // 针对table td的特殊处理
                                if(oIns.localName === 'td'){
                                    _this._occupyDivIns(oIns);
                                }else if(oNear){
                                    if(_this._getDis(objs,oIns) > _this._getDis(objs,oNear)){
                                        _this._occupyDivOut(oNear);
                                    }else{
                                        _this._occupyDivIns(oIns);
                                    }
                                }else{
                                    _this._occupyDivIns(oIns);
                                }
                            }else{
                                _this._occupyDivOut(oNear); 
                            }
                        }
                    },100);
                };
                document.onmouseup = function(){
                    
                    _this.oUl.style.width = '';
                    _this.oUl.style.height = '';
                    clearTimeout(_this.timer);
                    if(ins){
                        btn.onmousedown = null;
                    }
                    _this._clearStyle(obj);
                    //当鼠标弹起时移出移动事件
                    document.onmousemove = null; 
                    // 停止时操作
                    _this._stopOpt(obj,ins);
                    document.onmouseup = null;
                    obj.style.zIndex = '';
                    _this._init();
                    return false;
                };
                return false;
            };
        },
         // 碰撞检测
         _colTest: function(obj1,obj2){
            var t1 = obj1.offsetTop;
            var r1 = obj1.offsetWidth+obj1.offsetLeft;
            var b1 = obj1.offsetHeight+obj1.offsetTop;
            var l1 = obj1.offsetLeft;
            var t2 = obj2.offsetTop;
            var r2 = obj2.offsetWidth+obj2.offsetLeft;
            var b2 = obj2.offsetHeight+obj2.offsetTop;
            var l2 = obj2.offsetLeft;

            if(t1>b2||r1<l2||b1<t2||l1>r2){
                return false;
            }else{
                return true;
            }
        },
        //勾股定理求距离
        _getDis: function(obj1,obj2){
            var a = obj1.offsetLeft-obj2.offsetLeft;
            var b = obj1.offsetTop-obj2.offsetTop;
            return Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
        },
        // 获取页面滚动出去的距离
        _getScroll: function() {
          var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
          var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
          return {
            scrollLeft: scrollLeft,
            scrollTop: scrollTop
          };
        },

        // ie8判断
        ie8:function(callback){
            if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE8.0"){
                typeof callback == "function" ? callback() : null;
            }
        }
    };
    window.dragLay = dragLay;
  })(window, document);


  layui.define([], function(exports){
    exports('dragLay', dragLay);
  });
  